package com.ms.services.ftp;


import com.ms.exception.DpwcException;
import com.ms.util.FileUtil;
import it.sauronsoftware.ftp4j.FTPClient;
import it.sauronsoftware.ftp4j.FTPDataTransferListener;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by RAZANERO on 31/01/14.
 */
public class FtpUtil {
    private static final Logger LOG = LoggerFactory.getLogger(FtpUtil.class);

    public static List<String> getFileList(FtpBean ftpBean, String filter) throws Exception {
        List<String> fileList = new ArrayList<String>();
        FTPClient ftpClient = null;

        try {
            ftpClient = new FTPClient();
            ftpClient.connect(ftpBean.getHost());
            ftpClient.login(ftpBean.getUser(), ftpBean.getPassword());
            ftpClient.setPassive(true);
            ftpClient.changeDirectory(ftpBean.getDirectory());
            ftpClient.setType(FTPClient.TYPE_BINARY);


            String[] fileNameArray = ftpClient.listNames();

            if (fileNameArray != null) {
                for (String fileName : fileNameArray) {
                    if (fileName.startsWith(filter)) {
                        fileList.add(fileName);
                    }

                }
            }


        } catch (Exception e) {
            LOG.error("Error al enviar archivo por FTP", e);
            throw e;
        } finally {
            if (ftpClient != null && ftpClient.isConnected()) {
                ftpClient.disconnect(true);
            }
        }
        return fileList;
    }


    public static boolean send(FtpBean ftpBean) throws Exception {
        FTPClient ftpClient = null;
        LOG.debug("Ftp con datos " + ftpBean);
        if (ftpBean.getFile() == null)
            throw new DpwcException("Debe ingresar un archivo para transmitir al ftp");

        if (StringUtils.isBlank(ftpBean.getDirectory()))
            throw new DpwcException("Debe ingresar el directorio donde se copiara el archivo");

        try {
            ftpClient = new FTPClient();
            ftpClient.connect(ftpBean.getHost());
            ftpClient.login(ftpBean.getUser(), ftpBean.getPassword());
            ftpClient.setPassive(true);
            ftpClient.changeDirectory(ftpBean.getDirectory());
            ftpClient.setType(FTPClient.TYPE_BINARY);
            ftpClient.upload(ftpBean.getFile());
            return true;
        } catch (Exception e) {
            LOG.error("Error al enviar archivo por FTP", e);
            throw e;
        } finally {
            if (ftpClient != null && ftpClient.isConnected()) {
                ftpClient.disconnect(true);
            }
        }
    }

    public static File getFile(FtpBean ftpBean) throws Exception {
        FTPClient ftpClient = null;
        if (StringUtils.isBlank(ftpBean.getFileName()))
            throw new DpwcException("Debe ingresar el nombre para recuperar del ftp ");

        if (StringUtils.isBlank(ftpBean.getDirectory()))
            throw new DpwcException("Debe ingresar el directorio del archivo en el ftp");

        try {
            LOG.debug("conectar Ftp con datos " + ftpBean);
            ftpClient = new FTPClient();
            ftpClient.connect(ftpBean.getHost());
            ftpClient.setType(FTPClient.TYPE_BINARY);
            ftpClient.login(ftpBean.getUser(), ftpBean.getPassword());
            ftpClient.setPassive(true);
            ftpClient.changeDirectory(ftpBean.getDirectory());
            File result = FileUtil.createTempFile(".ZIP");
            ftpClient.download(ftpBean.getFileName(), result);
            ftpBean.setFileName(null);
            return result;
        } catch (Exception e) {
            LOG.error("Error al obtener el archivo por FTP", e);
            throw e;
        } finally {
            if (ftpClient != null && ftpClient.isConnected()) {
                ftpClient.disconnect(true);
            }
        }
    }

    public class MyTransferListener implements FTPDataTransferListener {

        public void started() {
            // Transfer started
        }

        public void transferred(int length) {
            // Yet other length bytes has been transferred since the last time this
            // method was called
        }

        public void completed() {
            // Transfer completed
        }

        public void aborted() {
            // Transfer aborted
        }

        public void failed() {
            throw new DpwcException("Error al copiar archivo al FTP");
        }

    }

}
